import { Provide } from '@midwayjs/decorator';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import { ConvenientType } from '../entity/ConvenientService';
import { TbFlow } from '../entity/TbFlow';
import { TbFlowLine } from '../entity/TbFlowLine';
import { TbFlowNode } from '../entity/TbFlowNode';

@Provide()
export class FlowService {
  @InjectEntityModel(TbFlow)
  flowModel: Repository<TbFlow>;

  @InjectEntityModel(TbFlowNode)
  flowNodeModel: Repository<TbFlowNode>;

  @InjectEntityModel(TbFlowLine)
  flowLineModel: Repository<TbFlowLine>;

  /**
   * 初始化二孩生育补贴流程
   */
  async initFlowEHSY() {
    // 检查是否已存在临时救助流程
    const instance = await this.flowModel.findOne({
      where: {
        convenientType: ConvenientType.EHSY,
      },
    });
    if (!instance) {
      // 创建流程
      const flow = new TbFlow();
      flow.name = '二孩生育补贴流程';
      flow.convenientType = ConvenientType.EHSY;
      await this.flowModel.save(flow);
      // 创建节点
      const nodes = this.flowNodeModel.create([
        { name: '受理', role: '计划生育窗口', flow },
        { name: '初审', role: '计生科', flow },
        { name: '审核', role: '卫计局', flow },
      ]);
      await this.flowNodeModel.save(nodes);
      // 创建线
      const lines = this.flowLineModel.create([
        { flow, prevNode: nodes[0], nextNode: nodes[1] },
        { flow, prevNode: nodes[1], nextNode: nodes[2] },
      ]);
      await this.flowLineModel.save(lines);
    }
  }
}
